/*
 * @Author: yangzonglong
 * @Date: 2021-01-25 09:56:52
 * @version: v1.0.0
 * @Descripttion: 通用pageHeader
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-02-19 14:38:51
 * @Auditor: 
 */
import React, { useMemo, useRef, useEffect, useState } from 'react';
import { PageHeader as AntdPageHeader, Breadcrumb } from 'antd';
import { PageHeaderProps } from 'antd/lib/page-header';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import Qs from 'query-string';
import i18n from '@library/app/i18n';
import { ModuleItemProps } from '@library/interface/userInfo';
import history from './../../app/history';
import { treeRoutesConfig } from './../../app/automatic/routes';
import { HOME_PATH, PACKAGE_NAME } from './../../app/automatic/package';
import { getRouteHistory } from './../../utils/footprint/footprint';
import Icon from './../icon/Icon';
import { Store } from './../../redux/store'
import { toggleCollapsed } from './../../redux/common'
import s from './pageHeader.module.scss';

const T = window.$app.t;
const Item = Breadcrumb.Item;
const iconStyle = { fontSize: '20px', marginRight: '10px' };
const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');

function matchRoutes(routes, pathname, _branch) {
    let branch = _branch || []
    routes.some(function (route) {
      var match = pathname.includes(route.path)
  
      if (match) {
        branch.push({
          route: route,
          match: match
        });
  
        if (route.routes) {
          matchRoutes(route.routes, pathname, branch);
        }
      }
  
      return match;
    });
    return branch;
}

const functionNameMap = {};
userInfo?.menuList?.forEach((app: ModuleItemProps) => {
  if(app.moduleCode === PACKAGE_NAME) {
    app.menu.forEach((group) => {
      group.children.forEach((menu: any) => {
        const key = '/' + menu.functionUrl.split(PACKAGE_NAME + '.')[1];
        functionNameMap[key.toLowerCase()] = i18n.language === 'en' ? (menu.functionEnName || menu.functionName) : menu.functionName
      })
    })
  }
})


interface BreadcrumbData {
  name: string;
  path: string
}
interface IProps extends Partial<PageHeaderProps> {
  customRouteName?: string | React.ReactNode; // 指定当前面包屑的名称
}

const PageHeader = (props: IProps) => {
  const boxdom = useRef<HTMLDivElement>(null);
  const query = Qs.parseUrl(window.location.href).query;
  const parentRoute = query.parentRoute;
  const queryCustomRouteName = query.customRouteName;

  const dispatch = useDispatch();
  const { collapsed } = useSelector((store: Store) => store.common);
  const [routeLevel, setRouteLevel] = useState(false); // 路由级别pageHeader
  const [breadcrumbData, setBreadcrumbData] = useState<BreadcrumbData[]>([]);

  useEffect(() => {
    const parentNode: any = boxdom.current?.parentNode;
    if (parentNode?.className.indexOf('routeAnimation') >= 0) setRouteLevel(true);
  }, [collapsed]);

  useEffect(() => {
    const routes = matchRoutes(treeRoutesConfig, history.location.pathname, []);

    const handleRouteLocal = () => {
      const arr = routes.map((item) => {
        let path = item.route.path as string;
        if(path === '/crud') path = history.location.pathname;
        const name = functionNameMap[path.toLowerCase()];

        return {
          path: item.route.path as string,
          name: name || T(path)
        }
      })

      if (parentRoute) {
        setBreadcrumbData([{ path: parentRoute as string, name: T(parentRoute as string) }, ...arr])
      } else {
        setBreadcrumbData(arr)
      }
    }

    handleRouteLocal()
  }, [history.location.pathname]);

  const Title = useMemo(() => {
    if (props.title) {
      if(typeof props.title === 'string') return window.$app.t(props.title);
      return props.title;
    }
    
    if (!routeLevel) {
      return functionNameMap[history.location.pathname.toLowerCase()] || T(history.location.pathname);
    }

    // 用户指定面包屑最后一级name
    const customRouteName = props.customRouteName || queryCustomRouteName;

    return (
      <Breadcrumb>
        <Item>
          <span className={s.cursorPointer} onClick={() => window.parent?.postMessage('GO_HOME', '*')}>
            {window.$app.t('homePage')}
          </span>
        </Item>
        {breadcrumbData.map((item, index) => {
          const last = index === breadcrumbData.length - 1;
          const name = !customRouteName ? item.name : last ? customRouteName : item.name;
          return (
            <Item key={item.path}>
              { last ? name : <Link onClick={() => history._isFromBreadcrumb = true} to={getRouteHistory(item.path)}>{name}</Link> }
            </Item>
          )
        })}
      </Breadcrumb>
    );
  }, [breadcrumbData, props.title, props.customRouteName, routeLevel]);

  const Extra = useMemo(() => (props.extra ? <div className={s.searchBtn}>{props.extra}</div> : null), [props.extra]);

  return (
    <div className={s.pageHeader} ref={boxdom}>
      {collapsed && routeLevel && <Icon style={iconStyle} onClick={() => dispatch(toggleCollapsed(false))} icon="&#xe649;" />}
      <AntdPageHeader {...props} title={Title} extra={Extra} />
    </div>
  );
};

export default PageHeader;
